#!/usr/bin/python
# -*- coding: utf-8 -*-


import paramiko
import datetime
import os
import sys


#paramiko.util.log_to_file('paramiko.log',level='INFO')

def sshCommand(hostname,cmd,username = 'root',password = '%TGB^YHN',port = 22):
    """
    执行ssh命令
    """
    s=paramiko.SSHClient()                 
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        s.connect(hostname = hostname,port=port,username=username, password=password,timeout=5)          
        #stdin,stdout,stderr=s.exec_command('free;df -h')
        stdin,stdout,stderr=s.exec_command(cmd)
        print """\033[32;1m#########################%s#########################\033[0m
        %s""" % (hostname,stdout.read())
        #print stdout.read()
        s.close()
    except Exception,e:
        print '\033[31;1m[ERROR]==>%s %s \033[0m' % (hostname,e)


def sshUploadFile(hostname,local_file = None,remote_file = None,filelist = None, 
                  username = 'root',password = '%TGB^YHN',port = 22):
    """
    文件上传
    """
    try:
        t=paramiko.Transport((hostname,port))
    except Exception,e:
        print "\033[31;1m[ERROR]==>%s %s \033[0m" % (hostname,e)
        sys.exit(0)

    if not filelist:
        #检查文件是否带目录
        dirname = os.path.dirname(local_file)
        if not dirname:
            local_file = os.path.join(os.getcwd(),local_file)
        
        if dirname == '.':
            local_file = os.path.join(os.getcwd(),local_file.replace('./',''))
    
        #如果远程保存目录为None,则表示跟随本地文件目录
        if not remote_file:
            remote_file = local_file

    try:
        t.connect(username=username,password=password) 
        sftp=paramiko.SFTPClient.from_transport(t)
        #remote_file = os.path.join(remote_dir,os.path.basename(local_file))
    except paramiko.AuthenticationException,e:
        print "\033[31;1m[Error]==>%s %s \033[0m" % (hostname,e)
        sys.exit(0)
        
    #print '################################################################' 
    #print 'Begin to upload file  to %s %s' % (hostname,datetime.datetime.now() )

    try:
        if not filelist:
            #print 'Uploading %s to remote %s ' % (local_file,remote_file)
            sftp.put(local_file,remote_file)
            print '\033[32;1mUploading %s to %s success %s \033[0m' % (local_file,hostname,datetime.datetime.now())
        else:
            try:
                fp = open(filelist).readlines()
            except IOError,e:
                #文件打开失败
                print '\033[31;1m[ERROR]==>%s %s \033[0m' % (hostname,e)
                sys.exit(0)
                
            for local_file in fp:
                #忽略开头是井号的
                if local_file[0] == '#' or len(line.strip()) == 0:
                    continue                
                transfile = local_file.strip()
                if len(transfile) != 0:
                    #print 'Uploading %s to remote %s ' % (transfile,transfile)
                    sftp.put(transfile,transfile)
                    print '\033[32;1mUploading %s to %s success %s \033[0m' % (transfile,hostname,datetime.datetime.now())

                
    except IOError,e:
        #远程目录不存在
        print '\033[31;1m[ERROR]==>%s %s \033[0m' % (hostname,e)
    except OSError,e:
        #本地目录文件不存在
        print '\033[31;1m[ERROR]==>%s %s \033[0m' % (hostname,e)

    t.close()



def sshUploadDirFile(hostname,local_dir,remote_dir = '/tmp',username = 'root',password = '%TGB^YHN',port = 22):
    """
    文件上传,执行一个目录下的文件上传,不能包含子目录
    """
    t=paramiko.Transport((hostname,port))

    try:
        files=os.listdir(local_dir)
    except OSError,e:
        #本地目录不存在
        print "\033[31;1m Error %s %s \033[0m" % (hostname,e)
        sys.exit()

    try:
        t.connect(username=username,password=password) 
        sftp=paramiko.SFTPClient.from_transport(t)

        print '################################################################' 
        print 'Begin to upload file  to %s %s' % (hostname,datetime.datetime.now() )
        print 'Uploading %s to remote %s ' % (local_dir,remote_dir)
        for f in files:
            remote_file = os.path.join(remote_dir,os.path.basename(f))
            try:
                sftp.put(f,remote_file)
                print '\033[32;1mUploading %s success %s \033[0m' % (f,datetime.datetime.now())
            except IOError,e:
                #远程目录不存在
                print '\033[31;1mUploading %s fail %s \033[0m' % (f,datetime.datetime.now())

        print '################################################################' 
        t.close()
    except paramiko.AuthenticationException,e:
        #验证失败
        print "\033[31;1m Error %s %s \033[0m" % (hostname,e)
